package com.gitee.form_token.controller;

import cn.hutool.core.lang.UUID;
import cn.hutool.core.map.MapUtil;
import com.gitee.form_token.common.RedisUtil;
import com.gitee.form_token.common.Result;
import com.gitee.form_token.dto.LoginDto;
import com.gitee.form_token.service.MyLoginService;
import com.gitee.form_token.service.MyLogoutService;
import com.gitee.form_token.service.MyRegiterService;
import com.google.code.kaptcha.Producer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import sun.misc.BASE64Encoder;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

@Slf4j
@RestController
@RequestMapping("/auth")
public class AuthController {

    @Autowired
    private RedisUtil redisUtil;

    @Resource
    private MyLoginService myLoginService;

    @Resource
    private MyLogoutService myLogoutService;

    @Resource
    private MyRegiterService myRegiterService;

    @Resource
    private Producer producer;

    @GetMapping({"/captcha"})
    @ResponseBody
    public Result captcha(HttpServletRequest request) throws IOException {

        // 生成 base64
        BASE64Encoder base64 = new BASE64Encoder();

        // 字节数组输出流
        ByteArrayOutputStream baoStream = new ByteArrayOutputStream();

        // 生成/输出图片
        String code = producer.createText();
        BufferedImage image = producer.createImage(code);

        ImageIO.write(image, "png", baoStream);
        String base64Img = "data:image/png;base64," + base64.encode(baoStream.toByteArray());

        String uuid = UUID.randomUUID().toString();
        redisUtil.set(uuid, code, 120);
        log.info("生成验证码 code：{}，key：{}", code, uuid);

        return Result.success(MapUtil.builder()
                .put("uuid", uuid)
                .put("base64Img", base64Img)
                .build()
        );
    }

    @CrossOrigin
    @PostMapping("/login")
    public Result login(@Validated @RequestBody LoginDto user) {

        /****************************** 验证码 start ******************************/

        String code = user.getCode();
        String uuid = user.getUuid();

        if (code == null || uuid == null) {
            return Result.fail("验证码为空");
        }

        String login_code = (String) redisUtil.get(uuid);
        log.info("校验验证码 code：{}，key：{}", code, uuid);

        if (!code.equals(login_code)) {
            return Result.fail("验证码错误");
        }

        // 清除验证码
        redisUtil.del(uuid);

        /****************************** 验证码 end ******************************/

        return myLoginService.checkLogin(user);
    }

    @PostMapping("/register")
    public Result register(@Validated @RequestBody LoginDto loginDto) {

        /****************************** 验证码 start ******************************/

        String code = loginDto.getCode();
        String uuid = loginDto.getUuid();

        if (code == null || uuid == null) {
            return Result.fail("验证码为空");
        }

        String login_code = (String) redisUtil.get(uuid);
        log.info("验证码校验 code：{}，key：{}", code, uuid);

        if (!code.equals(login_code)) {
            return Result.fail("验证码错误");
        }

        // 清除验证码
        redisUtil.del(uuid);

        /****************************** 验证码 end ******************************/

        return myRegiterService.register(loginDto);
    }

    @GetMapping("/logout")
    public Result logout(HttpServletRequest request) {
        return myLogoutService.logout(request);
    }
}
